//
//  ReadDetailViewController.m
//  Leisure
//
//  Created by 大展 on 16/4/19.
//  Copyright © 2016年 张展. All rights reserved
//

#import "ReadDetailViewController.h"

// 数据类型
typedef enum {

    addtimeType, // 最新
    hotType      // 最热

}DataType;

@interface ReadDetailViewController ()<UITableViewDataSource,UITableViewDelegate>
@property (strong, nonatomic) IBOutlet UITableView *addtimeTableView; // 最新列表
@property (strong, nonatomic) IBOutlet UITableView *hotTableView;  // 最热列表
@property (strong, nonatomic) IBOutlet UISegmentedControl *segmentControl; // 分段视图控制器
@property (strong, nonatomic) IBOutlet UIScrollView *scrollView; // 滚动视图
@property (nonatomic, strong) NSMutableDictionary *parameter; // 请求参数
@property (nonatomic, strong)NSMutableArray *addtimeDataSource; // 存放最新数据的数组
@property (nonatomic, strong) NSMutableArray *hotSourceData; // 存放最热数据的数组
@property (nonatomic, assign) DataType dataType; // 数据类型

@property (nonatomic, assign) NSInteger hotStartInteger; // 加载数据的起始位置
@property (nonatomic, assign) NSInteger addTimestartInteger;
@property (nonatomic, assign) NSInteger hotStartCount;
@property (nonatomic, assign) NSInteger addTimestartCount;


@end

@implementation ReadDetailViewController

// segmentControl点击事件
- (IBAction)clickSegmentControlAction:(UISegmentedControl *)sender {
    /**
     *  通过segmentControl的下标来判断当前应显示哪一个tableView
     */
    switch (sender.selectedSegmentIndex) {
            // 最新
        case 0:

            [self.scrollView setContentOffset:CGPointMake(0, 0) animated:YES];
            break;

            // 最热
        case 1:
            [self.scrollView setContentOffset:CGPointMake(kWidth, 0) animated:YES];

            break;
        default:
            break;
    }
}


- (void)scrollViewDidScroll:(UIScrollView *)scrollView {

    // 如果当前滑动的滚动视图是我们自己的scrollView
    if (scrollView == self.scrollView) {

        /**
         *  通过滑动视图的偏移量来判断当前的segmentControl下标
         */
        if (scrollView.contentOffset.x == 0) {

            self.segmentControl.selectedSegmentIndex = 0;
            // 设置参数和请求体
            self.dataType = addtimeType;
            [self.parameter setObject:@"addtime" forKey:@"sort"];

        }else if(scrollView.contentOffset.x == kWidth) {
            // 最热
            self.segmentControl.selectedSegmentIndex = 1;
            // 设置参数和请求类型
            self.dataType = hotType;
            [self.parameter setValue:@"hot" forKey:@"sort"];
            // 如果数组不为空不再请求
            if (self.hotSourceData.count == 0) {

                [self fetchSourceDataWithUrl:kReadDetailUrl parameter:self.parameter dateType:addtimeType];
            }

        }
    }
}

// 根据网址去请求数据
- (void)fetchSourceDataWithUrl:(NSString *)url parameter:(NSMutableDictionary *)parameter dateType:(DataType)dateType {

    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    dispatch_async(dispatch_get_global_queue(0, 0), ^{

        // 添加菊花图

        // 初始化AFN请求工具
        AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
        // 设置请求类型
        manager.responseSerializer = [AFHTTPResponseSerializer serializer];
        // 开始请求
        [manager POST:url parameters:parameter progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {

            NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:responseObject options:(NSJSONReadingAllowFragments) error:nil];

            NSLog(@"_____%@",dic);

            NSArray *listArray = dic[@"data"][@"list"];

            if (dateType == addtimeType) {
                self.addTimestartCount = listArray.count;
            } else {
                self.hotStartCount = listArray.count;
            }

            for (NSDictionary *object in listArray) {

                ReadDetailModel *model = [[ReadDetailModel alloc]init];
                [model setValuesForKeysWithDictionary:object];

                if (self.dataType == addtimeType) {

                    [self.addtimeDataSource addObject:model];
                }else {
                    [self.hotSourceData addObject:model];
                }
            }
            dispatch_async(dispatch_get_main_queue(), ^{

                [self.addtimeTableView reloadData];
                [self.hotTableView reloadData];
                ////////////刷新
                [self.hotTableView.mj_header endRefreshing];
                [self.addtimeTableView.mj_header endRefreshing];
                [self.hotTableView.mj_footer endRefreshing];
                [self.addtimeTableView.mj_footer endRefreshing];


                [MBProgressHUD hideHUDForView:self.view animated:YES];
            });
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {

            //        NSLog(@"0");
        }];
    });

}

#pragma mark ------UITableViewDelegate-----

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {

    // 如果是最新列表的话，返回最新数据的数组的个数
    if (tableView == self.addtimeTableView) {

        return self.addtimeDataSource.count;
    } else if(tableView == self.hotTableView){

        return self.hotSourceData.count;
    }
    return 0;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    ReadDetailCell *cell = [tableView dequeueReusableCellWithIdentifier:@"readDetial_cell" forIndexPath:indexPath];

    ReadDetailModel *model = [[ReadDetailModel alloc]init];
    if (tableView == self.addtimeTableView) {

        model = self.addtimeDataSource[indexPath.row];
    } else if (tableView == self.hotTableView) {

        model = self.hotSourceData[indexPath.row];
    }

    [cell setCellWithModel:model];
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {

    return 150;
}

// 点击进入详情
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {

    // 获取model
    ReadDetailModel *model = [[ReadDetailModel alloc]init];
    // 判断点击的是哪一个tableView
    if (tableView == self.addtimeTableView) {
        model = self.addtimeDataSource[indexPath.row];


    } else if (tableView == self.hotTableView) {

        model = self.hotSourceData[indexPath.row];

    }

    //从storyBoard里面去获取控制器
    ReadInfoViewController *readInoVC = [self.storyboard instantiateViewControllerWithIdentifier:@"ReadInfoViewController"];

    // 属性传值
    readInoVC.contentid = model.typeID;
    
    [self.navigationController pushViewController:readInoVC animated:YES];
}

- (void)viewDidLoad {
    [super viewDidLoad];

    self.automaticallyAdjustsScrollViewInsets = NO;

    // 注册xib Cell
    [self.addtimeTableView registerNib:[UINib nibWithNibName:@"ReadDetailCell" bundle:nil] forCellReuseIdentifier:@"readDetial_cell"];
    [self.hotTableView registerNib:[UINib nibWithNibName:@"ReadDetailCell" bundle:nil] forCellReuseIdentifier:@"readDetial_cell"];

    /********   hotTableView   ********/
    self.hotTableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        [self.hotTableView.mj_header beginRefreshing];
        self.hotStartInteger = 0;
        self.hotSourceData = nil;
        [self.parameter setValue:[NSNumber numberWithInteger:self.hotStartInteger] forKey:@"start"];

        //下拉刷新网络请求
        [self fetchSourceDataWithUrl:kReadDetailUrl parameter:self.parameter dateType:hotType];

    }];

    self.hotTableView.mj_footer = [MJRefreshBackFooter footerWithRefreshingBlock:^{

        self.hotStartInteger += 10;
        [self.parameter setValue:[NSNumber numberWithInteger:self.hotStartInteger] forKey:@"start"];
        [self.parameter setValue:@"hot" forKey:@"sort"];
        [self fetchSourceDataWithUrl:kReadDetailUrl parameter:self.parameter dateType:self.dataType];
    }];

    /********   addtimeTableView   ********/
    self.addtimeTableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        [self.addtimeTableView.mj_header beginRefreshing];
        self.addTimestartInteger = 0;
        self.addtimeDataSource = nil;
        [self.parameter setValue:[NSNumber numberWithInteger:self.addTimestartInteger] forKey:@"start"];
        //下拉刷新网络请求
        [self fetchSourceDataWithUrl:kReadDetailUrl parameter:self.parameter dateType:addtimeType];

    }];
    self.addtimeTableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        self.addTimestartInteger += 10;
        [self.parameter setValue:[NSNumber numberWithInteger:self.addTimestartInteger] forKey:@"start"];

        if (self.addTimestartCount < 10) {
            //提示已经加载所有数据
        } else {
            //上拉加载，网络请求
            [self fetchSourceDataWithUrl:kReadDetailUrl parameter:self.parameter dateType:addtimeType];
        }
    }];

    // 最初的数据类型为最新
    self.dataType = addtimeType;
    [self fetchSourceDataWithUrl:kReadDetailUrl parameter:self.parameter dateType:addtimeType];


}

#pragma mark -------懒加载-------

// 懒加载参数
- (NSMutableDictionary *)parameter{

    if (!_parameter) {

        _parameter = [NSMutableDictionary dictionaryWithDictionary:@{@"sort":@"addtime",@"limit":@10,@"typeid":[NSNumber numberWithInteger:self.typeID],@"start":@0}];
    }
    return _parameter;
}

- (NSMutableArray *)addtimeDataSource {
    
    if (!_addtimeDataSource) {
        _addtimeDataSource = [NSMutableArray array];
    }
    return _addtimeDataSource;
}

- (NSMutableArray *)hotSourceData {
    
    if (!_hotSourceData) {
        
        _hotSourceData = [NSMutableArray array];
    }
    return _hotSourceData;
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


@end
